package org.iks.user.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.iks.common.util.ServletUtil;
import org.iks.feign.service.store.SessionRemoteService;
import org.iks.user.web.entity.FriendEntity;
import org.iks.user.web.entity.UserEntity;
import org.iks.user.web.mapper.FriendMapper;
import org.iks.user.web.service.FriendService;
import org.iks.user.web.service.UserService;
import org.iks.user.web.vo.UserFriendRespVo;
import org.iks.user.web.vo.UserInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * Author kzou
 * Date 2024/2/13
 * Description:
 */
@Service
public class FriendServiceImpl extends ServiceImpl<FriendMapper, FriendEntity> implements FriendService {

    @Autowired
    private UserService userService;

    @Autowired
    private SessionRemoteService sessionService;

    @Override
    public List<UserFriendRespVo> queryFriends(String userAccount) {
        List<UserFriendRespVo> respVos = baseMapper.queryUserFriends(userAccount);
        for (UserFriendRespVo respVo : respVos) {
            String friendAccount = Objects.equals(respVo.getUserAccount(), userAccount)
                    ? respVo.getCreatorAccount()
                    : respVo.getUserAccount();
            UserEntity userEntity = userService.queryUserByAccount(friendAccount);
            respVo.setFriendUserInfo(UserInfoVo.valueOf(userEntity));
        }
        return respVos;
    }

    @Override
    public void addFriend(String userAccount) {
        String account = ServletUtil.currUser().account();
        FriendEntity friendEntity = new FriendEntity();
        friendEntity.setCreateTime(new Date());
        friendEntity.setUserAccount(userAccount);
        friendEntity.setCreatorAccount(account);
        sessionService.createDefaultSession(userAccount);
        baseMapper.insert(friendEntity);
    }

    @Override
    public int deleteFriend(String creatorAccount, String account) {
        LambdaQueryWrapper<FriendEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FriendEntity::getUserAccount, creatorAccount)
                .eq(FriendEntity::getCreatorAccount, account)
                .or(r -> r.eq(FriendEntity::getUserAccount, account)
                        .eq(FriendEntity::getCreatorAccount, creatorAccount));
        return baseMapper.delete(queryWrapper);
    }

}
